<template>
  <el-dialog :visible.sync="dialogVisible" :title="mode === 'add' ? '新增店铺' : '编辑店铺'" :close-on-click-modal="false" fullscreen="" center @close="close">
    <div v-if="mode != 'add'" class="instructions">
      <h3>说明</h3>
      <p>商户数据同步来源于享扫超管数据配置，该数据同步类型为不可编辑，不支持门店添加，如果需要添加门店，请到享扫。</p>
    </div>
    <!-- :disabled="mode === 'add' ? false : true" -->
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" label-width="130px" size="small" class="form-main" :disabled="form_disabled">
      <el-form-item label="店铺logo：" prop="icon">
        <div class="app-upload-container flex-x-start-center">
          <el-upload
            :action="uploadImgApi"
            :show-file-list="false"
            :headers="{ 'X-SERVICER-TOKEN': $store.state.user.token }"
            :before-upload="uploadImgBefore"
            :on-progress="uploadImgProgress"
            :on-error="uploadImgError"
            :on-success="uploadImgSuccess"
            class="upload-box"
          >
            <el-image v-if="form.icon" :src="fileBaseUrl + form.icon" class="upload-img" fit="contain" />
            <i v-else class="el-icon-plus" />
          </el-upload>
          <el-button v-if="form.icon" type="text" round size="small" class="app-color-danger" style="padding-left: 10px" @click="form.icon = null">删除</el-button>
        </div>
        <div class="app-tips">仅支持JPG/PNG文件，建议像素300px * 300px，且不超过500KB</div>
      </el-form-item>
      <el-form-item label="店铺名称：" prop="name"><el-input v-model="form.name" maxlength="32" show-word-limit placeholder="请输入" /></el-form-item>
      <el-form-item label="支付门店编号：" prop="storeNo"><el-input v-model="form.storeNo" maxlength="30" show-word-limit placeholder="请输入" /></el-form-item>
      <el-form-item label="联系电话：" prop="mobilePhone"><el-input v-model="form.mobilePhone" maxlength="11" show-word-limit placeholder="请输入" /></el-form-item>
      <el-form-item label="店铺地址：" prop="address">
        <el-form-item prop="provinceCode">
          <el-cascader v-model="mapRegion" size="small" style="width:100%;" :options="mapRegionOptions" @change="mapRegionDataChange" />
        </el-form-item>
        <el-input v-model="form.address" type="textarea" maxlength="100" show-word-limit :autosize="{ minRows: 2 }" placeholder="请输入" />
      </el-form-item>

      <el-form-item label="店铺位置：" prop="latitude">
        <div class="tencent-map-box"><TencentMap :tencent-map-src="tencentMapSrc" @getPackingLocation="getPackingLocation" /></div>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" round :disabled="loading" @click="hide">取 消</el-button>
      <!-- :disabled="mode === 'add' ? false : (mode != 'add' ? true : loading)" -->
      <el-button size="small" round type="primary" @click="submitForm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import TencentMap from '@/components/TencentMap'
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
import { mapGetters } from 'vuex'
import { uploadImgApi } from '@/api/upload'
import { addShop, editShop } from '@/api/mch/shop'
import { validMobilePhone } from '@/utils/validate'

export default {
  components: {
    TencentMap
  },
  data() {
    /**
		 * 表单校验方法相关
		 */
    // 手机号
    const validateMobilePhone = (rule, value, callback) => {
      if (this.$isNull(value)) {
        callback(new Error('请输入手机号码'))
      } else if (!validMobilePhone(value)) {
        callback(new Error('请输入11位手机号'))
      } else {
        callback()
      }
    }
    return {
      // 校验字段
      rules: {
        // Logo图
        icon: [
          {
            required: true,
            message: '请上传门店logo图',
            trigger: ['change']
          }
        ],
        // 名称
        name: [
          {
            required: true,
            message: '请输入店铺名称',
            trigger: ['blur', 'change']
          }
        ],
        // 手机号
        mobilePhone: [
          {
            required: true,
            validator: validateMobilePhone,
            trigger: ['blur', 'change']
          }
        ],
        // 支付门店编号
        storeNo: [
          {
            required: true,
            message: '请输入支付门店编号',
            trigger: ['blur', 'change']
          }
        ],
        // 地址
        address: [
          {
            required: true,
            message: '请输入店铺地址',
            trigger: ['blur', 'change']
          }
        ],
        // 名称
        latitude: [
          {
            required: true,
            message: '请选择店铺位置',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      title: null,
      resolve: null,
      reject: null,
      uploadImgApi: uploadImgApi,
      mapRegionOptions: regionData,
      // 状态
      dialogVisible: false,
      loading: false,
      // 数据
      mode: 'add',
      form: {
        businessId: null,
        icon: 'business/logo/kun_store.jpg',
        name: null,
        mobilePhone: null,
        address: null,
        latitude: null,
        storeNo: null,
        longitude: null,
        provinceCode: null,
        cityCode: null,
        areaCode: null
      },
      tencentMapSrc: 'https://apis.map.qq.com/tools/locpicker?coord=113.403181,23.163261&search=1&type=1&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&referer=myapp&zoom=18',
      mapRegion: ['440000', '440100', '440106'],

	  form_disabled: false
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl', 'userInfo'])
  },
  watch: {},
  beforeCreate() {},
  created() {},
  beforeMount() {},
  mounted() {},
  beforeUpdate() {},
  update() {},
  activated() {},
  deactivated() {},
  beforeDestroy() {},
  destroyed() {},
  methods: {
    // 弹框相关
    open({ mode = 'add', row = null }) {
      this.mode = mode
      if (mode === 'add') {
        this.mapRegionDataChange(this.mapRegion)
      } else {
        const params = Object.assign({}, row)
        this.tencentMapSrc = `https://apis.map.qq.com/tools/locpicker?coord=${params.longitude || 113.403181},${params.latitude ||
					23.163261}&search=1&type=1&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&referer=myapp&zoom=18`
        if (params.provinceCode) {
          this.mapRegion = [
            TextToCode[params.provinceCode].code,
            TextToCode[params.provinceCode][params.cityCode].code,
            TextToCode[params.provinceCode][params.cityCode][params.areaCode].code
          ]
        }
        this.form = params
      }
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true

	  // 设置修改权限
	  const source = this.userInfo.source
	  if (source == '0') {
	    this.form_disabled = false
	  } else if (source == '1') {
	    this.form_disabled = true
	  }
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    close() {
      this.mode = 'add'
      this.form = {
        businessId: null,
        icon: 'business/logo/kun_store.jpg',
        name: null,
        mobilePhone: null,
        address: null,
        latitude: null,
        storeNo: null,
        longitude: null,
        provinceCode: null,
        cityCode: null,
        areaCode: null
      }
      this.tencentMapSrc = 'https://apis.map.qq.com/tools/locpicker?coord=113.403181,23.163261&search=1&type=1&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&referer=myapp&zoom=18'
      this.mapRegion = ['440000', '440100', '440106']
      this.$refs.form.resetFields()
      this.loading = false
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.mode === 'add' ? this.add() : this.edit()
        }
      })
    },

    /**
		 * 数据组
		 */

    /**
		 * 按钮组
		 */
    // 新增
    add() {
      this.loading = true
      const params = Object.assign({}, this.form)
      params.businessId = this.$route.query.mchId
      addShop({ data: params })
        .then(() => {
          this.$root.$emit('refreshMchStoreList')
          this.$notify({
            title: '成功',
            message: '新增成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
          this.hide()
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 编辑
    edit() {
      this.loading = true
      const params = Object.assign({}, this.form)
      editShop({ data: params })
        .then(() => {
          this.$root.$emit('refreshMchStoreList')
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
          this.hide()
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 上传图片前
    uploadImgBefore(file) {
      return this.$uploadImgBefore({ file, maxSizes: 0.5, fileType: ['JPG', 'PNG'] })
    },

    // 上传图片中
    uploadImgProgress() {
      this.loading = true
    },

    // 上传图片错误
    uploadImgError() {
      this.loading = false
    },

    // 上传图片成功
    uploadImgSuccess(res) {
      this.loading = false
      if (res.code === 0) {
        this.form.icon = res.data.path
        this.$refs.form.clearValidate(['icon'])
      } else {
        this.$message.error(res.code + ':' + res.msg)
      }
    },

    // 腾讯地图
    getPackingLocation(res) {
      this.form.latitude = res.latlng.lat
      this.form.longitude = res.latlng.lng
      this.$refs.form.clearValidate(['latitude', 'longitude'])
    },

    /**
		 * 状态组
		 */
    // 地区变更
    mapRegionDataChange(val) {
      this.form.provinceCode = CodeToText[val[0]]
      this.form.cityCode = CodeToText[val[1]]
      this.form.areaCode = CodeToText[val[2]]
      this.$nextTick(() => {
        this.$refs.form.clearValidate(['provinceCode', 'cityCode', 'areaCode'])
      })
    }
    /**
		 * 方法组
		 */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.instructions {
	width: 50%;
	border: 1px solid #dcdfe6;
	padding: 16px;
	box-sizing: border-box;
	margin: 50px auto;
	margin-top: 15px;
	h3 {
		margin: 0;
	}
}

.form-main {
	width: 800px;
	margin: 0 auto;

	.tencent-map-box {
		width: 100%;
		height: 580px;
	}
}

/*上传*/
.app-upload-container {
	::v-deep.el-upload {
		width: 100px;
		height: 100px;
	}

	.upload-img {
		width: 100px;
		height: 100px;
	}

	.el-icon-plus {
		line-height: 100px;
	}
}
</style>
